package main

import (
	"context"
	"github.com/google/uuid"
	"gopkg.in/ini.v1"
	"io/ioutil"
	"log"
	"net/http"

	"github.com/tsuna/gohbase"
	"github.com/tsuna/gohbase/hrpc"
)

func welcomeHandler(w http.ResponseWriter, r *http.Request) {
	// 读取请求的 body
	body, err := ioutil.ReadAll(r.Body)
	if err != nil {
		http.Error(w, "Failed to read request body", http.StatusBadRequest)
		return
	}

	// 将 body 转换为字符串
	data := string(body)

	log.Printf("data:%s", data)
	// 返回成功响应
	w.WriteHeader(http.StatusOK)
	w.Write([]byte("successfully"))
}

// 处理插入数据的 HTTP 请求
func insertHandler(w http.ResponseWriter, r *http.Request, zk string) {
	// 读取请求的 body
	body, err := ioutil.ReadAll(r.Body)
	if err != nil {
		http.Error(w, "Failed to read request body", http.StatusBadRequest)
		return
	}

	// 将 body 转换为字符串
	data := string(body)
	log.Printf("data:%s", data)

	// 列族和列名
	family := "S"
	column := "column1"
	tableName := "TEST001"

	rowKey := generateRowKey()
	// 创建 HBase 客户端
	client := gohbase.NewClient(zk)

	// 创建插入数据的请求
	putRequest, err := hrpc.NewPutStr(context.Background(), tableName, rowKey, map[string]map[string][]byte{
		family: {
			column: []byte(data),
		},
	}, nil)
	if err != nil {
		http.Error(w, "Failed to create put request", http.StatusInternalServerError)
		return
	}

	// 发送插入数据的请求
	_, err = client.Put(putRequest)
	if err != nil {
		http.Error(w, "Failed to put data", http.StatusInternalServerError)
		return
	}

	// 返回成功响应
	w.WriteHeader(http.StatusOK)
	w.Write([]byte("Data inserted successfully"))
}

func handlerWrapper(param string) http.HandlerFunc {
	return func(w http.ResponseWriter, r *http.Request) {
		insertHandler(w, r, param)
	}
}

func main() {
	// 加载INI文件
	cfg, err := ini.Load("config.ini")
	if err != nil {
		log.Println("Failed to load INI file:", err)
		return
	}

	// 获取某个section下的key的值
	zk := cfg.Section("").Key("zk").String()

	// 注册插入数据的处理函数
	http.HandleFunc("/", welcomeHandler)
	// 注册插入数据的处理函数
	http.HandleFunc("/insert", handlerWrapper(zk))

	// 启动 HTTP 服务器
	log.Fatal(http.ListenAndServe(":8080", nil))
}

func generateRowKey() string {
	return uuid.New().String()
}
